import Api from '@/services/api.js';
import { checkPhoneNumber } from '@/utils/utils';
import { mapping } from '@/mixin/mixins/mapping';
const app = getApp();
export default {
  mixins: [mapping],
  components: {
  },
  data() {
    return {
      pickerType: '', // 选择类型
      department: {}, // 部门信息
      PRIMARY_TEXT_COLOR: app.globalData.PRIMARY_TEXT_COLOR,
      auditStatus: '-1', // 审核状态
      info: {
        corporateName: '', // 公司名称
        userName: '', // 联系人姓名
        contactPhone: '', // 联系电话
        category: '', // 行业
        categoryId: '', // 行业id
        userNum: '', // 规模
        userNumId: '', // 规模id
        contactJob: '', // 岗位
        contactJobId: '', // 岗位id
        businessImgUrl: '', // 营业执照
        logoUrl: ''  // 企业logo
      },
      industryList: [], // 行业列表
      postList: [], // 岗位列表
      scaleList: [], // 规模列表
    }
  },
  computed: {
    // 每一项填完之后才可以保存
    canSubmit() {
      return Object.keys(this.info).find(key => !this.info[key]);
    },
    statusObj() {
      return this.statusMapping[this.auditStatusMapping[this.auditStatus]];
    },
    // 是否禁用 审核中和审核成功的禁用
    isDisabled() {
      return this.auditStatus == 0 || this.auditStatus == 1;
    }
  },
  onLoad(options) {
    const { enterpriseInfo } = options;
    if (enterpriseInfo) {
      // 每一个返回的字段和传参的字段对应不上的， 都用别名对应
      const {
        id,
        title: userName,
        industryId_dictText: category,
        industryId: categoryId,
        userNumId_dictText: userNum,
        userNumId,
        contactJobId_dictText: contactJob,
        contactJobId,
        businessLicense: businessImgUrl,
        extinfor,
        auditStats
       } = JSON.parse(decodeURIComponent(enterpriseInfo));
      const { corporateName = '', contactPhone = '' } = JSON.parse(extinfor);
      this.auditStatus = auditStats;
      // 深拷贝一次  因为只有一层 直接用扩展运算符
      const deepClone = {...this.info};
      this.info = Object.assign(deepClone, {
        id, // 编辑数据 新增一个id
        corporateName,
        userName,
        contactPhone,
        category,
        categoryId,
        userNum,
        userNumId,
        contactJob,
        contactJobId,
        businessImgUrl
      })

      this.$refs.noticeModal.toggleModal(true);
    }
  },
  mounted() {
    this.getTypesByPid();
    this.getDicts();
  },
  methods: {
    // 获取数据字典
    async getTypesByPid() {
      const ret = await Promise.all([
        await this.$request({
          url: Api.getTypesByPid,
          data: {
            pid: this.dictsEnum.industryPid
          }
        }),
        await this.$request({
          url: Api.getTypesByPid,
          data: {
            pid: this.dictsEnum.enterprisePostPid
          }
        }),
      ])
      let industryResult = ret[0] || {};
      let postResult = ret[1] || {};
      if (industryResult?.code === 200) {
        this.industryList = industryResult.result.map(i => {
          i.key = i.id;
          i.val = i.name;
          return i;
        })
      }
      if (postResult?.code === 200) {
        this.postList = postResult.result.map(i => {
          i.key = i.id;
          i.val = i.name;
          return i;
        })
      }
    },
    // 获取数据字典
    async getDicts() {
      const ret = await this.$request({
        url: Api.getDicts,
        data: {
          key: this.dictsEnum.employeeNum
        }
      })
      if (ret.code == 200) {
        this.scaleList = ret.result.map(i => {
          i.val = i.title;
          i.key = i.value;
          return i;
        })
      }
    },
    handlePickerPop(e) {
      if (this.isDisabled) return;
      const { arr, value, type } = e.currentTarget.dataset;
      this.pickerType = type;
      this.$refs.commonPickerPop.togglePopup(true, { arr, value })
    },
    handleUpload(e) {
      if (this.isDisabled) return;
      const { type } = e.currentTarget.dataset;
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album'],
        success: async (res) => {
          const { tempFilePath } = res.tempFiles[0];
          const { code, message } = await this.$upload({ filePath: tempFilePath });
          if (code == 200) {
            switch (type) {
              case 'businessLicense':
                this.info.businessImgUrl = message;
                break;
              case 'logo':
                this.info.logoUrl = message;
                break;
            }
          }
        },
        fail: err => {
          console.log('err===>', err);
        }
      })
    },
    handleSubmit() {
      if (!this.info.corporateName.trim()) {
        return uni.showToast({ title: '请输入公司名称', icon: 'none' });
      }
      if (!this.info.userName.trim()) {
        return uni.showToast({ title: '请输入联系人姓名', icon: 'none' });
      }
      if (!this.info.contactPhone.trim()) {
        return uni.showToast({ title: '请输入联系电话', icon: 'none' });
      }
      if (!checkPhoneNumber(this.info.contactPhone)) {
        return uni.showToast({ title: '请输入正确的联系电话', icon: 'none' });
      }
      if (!this.info.categoryId.trim()) {
        return uni.showToast({ title: '请选择所在行业', icon: 'none' });
      }
      if (!this.info.userNumId.trim()) {
        return uni.showToast({ title: '请选择企业规模', icon: 'none' });
      }
      if (!this.info.contactJobId.trim()) {
        return uni.showToast({ title: '请选择本人岗位', icon: 'none' });
      }
      if (!this.info.businessImgUrl.trim()) {
        return uni.showToast({ title: '请上传营业执照', icon: 'none' });
      }
      if (!this.info.logoUrl.trim()) {
        return uni.showToast({ title: '请上传企业logo', icon: 'none' });
      }
      // 请求提交认证接口
      this.requestCert();
    },
    // 请求提交认证接口
    async requestCert() {
      const ret = await this.$request({
        url: Api.applyToBoss,
        method: 'POST',
        data: {
          ...this.info
        }
      })
      if (ret.code === 200) {
        uni.showToast({
          title: '操作成功',
          icon: 'none'
        })
        this.$store.commit('setStore', {
          privacyData: {
            enterpriseName: this.info.corporateName
          }
        })
        setTimeout(() => {
          uni.navigateBack();
        }, 500)
      }
    },
    onConfirm(e) {
      switch (this.pickerType) {
        case 'category':
          this.info.category = e.val;
          this.info.categoryId = e.key;
          break;
        case 'scale':
          this.info.userNum = e.val;
          this.info.userNumId = e.key;
          break;
        case 'post':
          this.info.contactJob = e.val;
          this.info.contactJobId = e.key;
          break;
      }
    }
  }
}